package com.powerbank.user.controller;

import com.powerbank.common.result.Result;
import com.powerbank.common.utils.JwtUtils;
import com.powerbank.user.service.BillingService;
import com.powerbank.user.vo.BillingInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 计费控制器
 */
@Slf4j
@RestController
@RequestMapping("/billing")
public class BillingController {

    @Autowired
    private BillingService billingService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 获取实时计费信息
     */
    @GetMapping("/current/{orderId}")
    public Result<BillingInfoVO> getCurrentBilling(@PathVariable Long orderId) {
        BillingInfoVO billingInfo = billingService.calculateCurrentBilling(orderId);
        return Result.success(billingInfo);
    }

    /**
     * 获取计费预览
     */
    @GetMapping("/preview")
    public Result<BillingInfoVO> getBillingPreview(HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        BillingInfoVO billingInfo = billingService.getBillingPreview(userId);
        return Result.success(billingInfo);
    }

    /**
     * 从请求中获取用户ID
     */
    private Long getUserIdFromToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            String token = bearerToken.substring(7);
            return jwtUtils.getUserIdFromToken(token);
        }
        throw new RuntimeException("Token不能为空");
    }
}